package com.ruoyi.finance.utils;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: tjk
 * @Date: 2025/2/28 13:54
 * @Description:
 **/
public class ThreadPoolExecutorExample {
    public static void main(String[] args) {
        int corePoolSize = 2;
        int maximumPoolSize = 4;
        long keepAliveTime = 60L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(10);

        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue
        );

        // 创建并提交任务
        for (int i = 0; i < 20; i++) {
            executor.submit(new Task(i));
        }

        // 优雅关闭线程池
        executor.shutdown();
    }
    // 定义任务
    static class Task implements Runnable {
        // 任务ID
        private final int taskId;
        // 构造函数
        public Task(int taskId) {
            this.taskId = taskId;
        }

        // 任务执行逻辑
        @Override
        public void run() {
            System.out.println("Executing task " + taskId + " by " + Thread.currentThread().getName());
        }
    }
}